﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OnlineStore.Bll;

namespace OnlineStore.Dal
{
    public class DalVoucher
    {
        OnlineStoreDataContext data = new OnlineStoreDataContext();
        public bool Update(Voucher VoucherItem)
        {
            try
            {
                var item = data.Vouchers.Single(p => p.Voucher_ID == VoucherItem.Voucher_ID);
                if (item == null) return false;
                item.Voucher_Price = VoucherItem.Voucher_Price;
                item.Status = VoucherItem.Status;
                item.Begin_Date = VoucherItem.Begin_Date;
                item.End_Date = VoucherItem.End_Date;
                data.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public Voucher LoadVoucher(int ID)
        {
            var _Voucher = (from p in data.Vouchers
                            where p.Voucher_ID == ID
                            select p).FirstOrDefault();
            return _Voucher;
        }
        public Voucher getVoucher(string Key)
        {
            var _Voucher = (from p in data.Vouchers
                            where p.Voucher_Key == Key
                            select p).FirstOrDefault();
            return _Voucher;
        }
        public bool SetUsingVoucher(Voucher VoucherItem)
        {
            Voucher item = data.Vouchers.Single(p => p.Voucher_Key == VoucherItem.Voucher_Key);
            if (item != null)
                item.Status = false;
            data.SubmitChanges();
            return true;
        }
        public List<Voucher> LoadAllVoucher()
        {
            var listVoucher = (from p in data.Vouchers
                               select p).ToList();
            return listVoucher;
        }
        public bool AddToVoucher(Voucher VoucherItem)
        {
            try
            {
                data.Vouchers.InsertOnSubmit(VoucherItem);
                data.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public int MaxID
        {
            get {
                var max = (from p in data.Vouchers
                           select p.Voucher_ID).ToList();
                if (max.Count == 0) return 0;
                return max.Max();
            }
        }
    }
}